<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Account Edit</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style type="text/css">
		input {
			font-size: 20px;
		}
		select {
			font-size: 20px;
		}
		
		a {
	      text-decoration:none;
	   	}
	</style>
	
	<script type="text/javascript">
		var role_list = new Array();
		var count = 0;
		var checkResetPassword = false;
		var role_delete = new Array();
		
		
		$(document).ready(function(){
			$('#tr_password_re').hide();
			
			count = document.getElementById("num_role").value;
			
			for(i=0; i<count; i++) {
				var ro = document.getElementById("td_role_add"+(i+1)).innerHTML.trim();
				role_list.push(ro);
				
			}
			
			$('#add').click(function(){
				var select = document.getElementById("role");
				var roleId = select.options[select.selectedIndex].value;
				var roleName = select.options[select.selectedIndex].text;
				
				if(roleId == "select") {
					alert("กรุณาเลือกหน้าที่ก่อนค่ะ");
				}
				else {
					var check_roleName = true;
					
					for(var i=0; i<role_list.length; i++) {
						if(roleName == role_list[i]) {
							alert(role_list[i]+" เลือกแล้วค่ะ");
							check_roleName = false;
						}
					}
					
					if(check_roleName) {
						count++;
						
						role_list.push(roleName);
						
						var input = '<input type="hidden" id="roleId_add'+count+'" name="roleId_add'+count+'" value="'+roleId+'" />';
						
						$('#table_role_add').append(input);
						
						var text = '<tr id="role_add'+count+'" name="role_add'+count+'" >'
									+ '<td style="height: 30px;">'
									+ roleName
									+ '</td>'
									+ '<td style="height: 30px;"> <center>'
									+ '<span title="ลบข้อมูล">'
									+ '<input type="image" src="image/delete_icon.png" height="30px" width="30px" onclick="delete_role('+count+')" />'
									+ '</span>'
									+ '</center> </td>'
									+ '</tr>';
						
						$('#table_role_add').append(text);
						
						var elem = document.getElementById("num_role");
						elem.value = count;
					}
				}
			});	
			
			$('#save').click(function(){
				var fullname = document.getElementById("name").value;
				var name = fullname.substr(0,fullname.indexOf(' '));
				var surname = fullname.substr(fullname.indexOf(' ')+1);
				
				var username = document.getElementById("username").value;
				
				var password = null;
				var passwordRe = null;
				if(checkResetPassword) {
					password = document.getElementById("password").value;
					passwordRe = document.getElementById("passwordRe").value;
				}				
				
				var check_error = "";
				
				var select = document.getElementById("workgroup");
				var workgroup = select.options[select.selectedIndex].value;
				if(workgroup == "select") {
					check_error = check_error + " หน่วยงาน";
				}
				
				var select2 = document.getElementById("status");
				var status = select2.options[select2.selectedIndex].value;
				if(status == "select") {
					check_error = check_error + " สถานะ";
				}
				
				var startDate = document.getElementById("startDate").value;
				if(!startDate) {
					check_error = check_error + " วันเริ่มต้นใช้งาน";
				}
				
				var check_endDate = true;
				var endDate = document.getElementById("endDate").value;
				if(!endDate) {
					check_endDate = false;
				}
				
				var num_role = document.getElementById("num_role").value;
				if(num_role == 0) {
					check_error = check_error + " หน้าที่";
				}
				
				if(check_error != "") {
					alert("กรุณาเลือก"+check_error+" ก่อนค่ะ");
				}
				else {
					
					// check password and re password
					if(checkResetPassword && password != passwordRe) {
						alert("password และ repassword ไม่ตรงกัน กรุณากรอกใหม่อีกครั้งค่ะ");
					}
					else {	
						/* AJAX */
						var xmlhttp;
						
						if(window.XMLHttpRequest) {
							// code for IE7+, Firefox, Chrome, Opera, Safari
							xmlhttp = new XMLHttpRequest();
						}
						else {
							// code for IE6, IE5
							xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
						}
						
						xmlhttp.onreadystatechange = function() {
							if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {									
								var result = xmlhttp.responseText.trim();
								if(result == "Success"){
									alert("บันทึกข้อมูลสำเร็จ");
									document.location.href = "admin_account.jsp";
								}else if(result == "Failed"){
									alert("บันทึกข้อมูลผิดพลาด กรุณาลองใหม่อีกครั้ง");
									document.location.href = "admin_account.jsp";
								}else if(result == "Special"){
									alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");
									document.location.href = "admin_account.jsp";
								}else if(result == "Noname"){
									alert("ไม่มีชื่อบุคคลนี้อยู่ในระบบค่ะ");
									//document.location.href = "admin_account.jsp";
								}
							}
						}
						
						var parameter = "name="+name+"&surname="+surname+"&username="+username+"&password="+password+"&workgroup="+workgroup
										+"&status="+status+"&startDate="+startDate+"&numRole="+num_role;
						// add parameter end date
						if(check_endDate) {
							parameter = parameter + "&endDate='"+endDate+"'";							
						}	
						else {
							parameter = parameter + "&endDate=null";
						}
						// add parameter role							
						for(i=0; i<num_role; i++) {
							var role = document.getElementById("roleId_add"+(i+1)).value;
							parameter = parameter + "&role"+(i+1)+"="+role;
						}
						// add parameter role delete
						parameter = parameter + "&numDelete="+role_delete.length;
						if(role_delete > 0) {
							for(i=0; i<role_delete.length; i++) {
								parameter = parameter + "&roleDelete"+(i+1)+"="+role_delete[i];
							}
						}
						
						//alert(parameter);//////////////try////////////
						
						xmlhttp.open("POST", "admin_account_edit_save.jsp?"+parameter, true);
						xmlhttp.send();
					}
				}		
			});		
			
		});		
		
		function delete_role(roleId, old) {	
			if(old) {
				var id = document.getElementById("roleId_add"+roleId).value;
				//alert("id : "+ id);///////////////try//////////////
				role_delete.push(id);
				//alert("size : "+ role_delete.length);///////////////try//////////////
			}
					
			$('#role_add'+roleId).remove();
			$('#roleId_add'+roleId).remove();
			
			for(var i=count; i>roleId; i--) {				
				var role_add = document.getElementById("role_add"+i);
				role_add.id = "role_add"+(i-1);  // using element properties
				role_add.setAttribute("name", "role_add"+(i-1));  // using .setAttribute() method
				
				var roleId_add = document.getElementById("roleId_add"+i);
				roleId_add.id = "roleId_add"+(i-1);  // using element properties
				roleId_add.setAttribute("name", "roleId_add"+(i-1));  // using .setAttribute() method
			}
			
			count--;

			var elem = document.getElementById("num_role");
			elem.value = count;
		}
		
		function reset_password() {
			var name_old = $('#name_old').val();
			var name_new = $('#name').val();
			
			if(name_old != name_new && name_new != "") {
				$('#resetPassword').hide();
				$('#tr_password_re').show();
				
				var input_password = '<input type="password" id="password" name="password" />'
									+ '<label><font size="5" color="#FF0000">*</font></label>';
				$('#td_password').append(input_password);
				
				checkResetPassword = true;
			}
			else {
				alert("กรุณาเปลี่ยนบุคคลใช้งานก่อนค่ะ");
			}
			
		}
		
		function search_name(name) {	
			if($('#namelist').find('option').length > 0) {
				
				$('#namelist').find('option').remove();
			}
			if(name != "") {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						
						
						var jsonObj = JSON.parse(xmlhttp.responseText);
						
						if(jsonObj.length == 0) {
							// no data
						}
						else{
							for(i in jsonObj) {
								var text = jsonObj[i].nameTH+" "+jsonObj[i].surnameTH;
								var option = '<option value="'+text+'" >';
								
								$('#namelist').append(option);
							}
						}
					}
				}
				
				xmlhttp.open("POST", "search_name_lec_emp.jsp?name="+name, true);
				xmlhttp.send();
			}			
		}
	</script>
</head>
<body>

<%
	// get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	// get parameter	
	String nameOld = new String(request.getParameter("name").getBytes("ISO8859_1"),"UTF-8");
	String surnameOld = new String(request.getParameter("surname").getBytes("ISO8859_1"),"UTF-8");
	String usernameOld = request.getParameter("username");
	String workgroupOld = new String(request.getParameter("workgroup").getBytes("ISO8859_1"),"UTF-8");
	int workgroupId = Integer.parseInt(request.getParameter("workgroupId"));
	String startDateOld = request.getParameter("startDate");
	String endDateOld = request.getParameter("endDate");
	String status = request.getParameter("status");
			
	System.out.println("EDIT nameOld "+nameOld);////////try////////
	System.out.println("EDIT surnameOld "+surnameOld);////////try////////
	System.out.println("EDIT usernameOld "+usernameOld);////////try////////
	System.out.println("EDIT workgroupOld "+workgroupOld);////////try////////
	System.out.println("EDIT workgroupId "+workgroupId);////////try////////
	System.out.println("EDIT startDateOld "+startDateOld);////////try////////
	System.out.println("EDIT endDateOld "+endDateOld);////////try////////
	System.out.println("EDIT status "+status);////////try////////
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find role of username in database */
	List<Role> role_old = new ArrayList<Role>();
	
	/* find workgroup in database */
	List<Workgroup> workgroup = new ArrayList<Workgroup>();
	
	/* find role in database */
	List<Role> role = new ArrayList<Role>();
	
	try {			
		/* find role of username in database */
		ResultSet rs_role_old = connect.createStatement().executeQuery("SELECT role_name, R.role_id " 
												+ " FROM authorization AU, role R " 
												+ " WHERE AU.role_id=R.role_id AND AU.username='" + usernameOld +"' " 
												+ " ORDER BY role_name");
		
		while(rs_role_old.next()) {
			Role ro = new Role();
			
			ro.setRoleName(rs_role_old.getString("role_name"));
			ro.setRoleId(rs_role_old.getInt("role_id"));
			
			role_old.add(ro);
		}
		
		/* find workgroup in database */
		ResultSet rs_wg = connect.createStatement().executeQuery("SELECT workgroup_name, workgroup_id " 
				+ " FROM  workgroup " 
				+ " ORDER BY  workgroup_name");
		
		while(rs_wg.next()) {
			Workgroup work = new Workgroup();
			
			work.setWorkgroupId(rs_wg.getInt("workgroup_id"));
			work.setWorkgroupName(rs_wg.getString("workgroup_name"));
			
			workgroup.add(work);
		}
	
		/* find role in database */
		ResultSet rs = connect.createStatement().executeQuery("SELECT role_id, role_name, permission, R.system_id, system_name, system_name_th " 
				+ " FROM role R, system S " 
				+ " WHERE R.system_id=S.system_id "
				+ " ORDER BY role_name");
		
		while(rs.next()) {
			Role rol = new Role();
			
			rol.setRoleId(rs.getInt("role_id"));
			rol.setRoleName(rs.getString("role_name"));
			rol.setPermission(rs.getString("permission"));
			rol.setSystemId(rs.getInt("system_id"));
			rol.setSystemName(rs.getString("system_name"));
			rol.setSystemNameTH(rs.getString("system_name_th"));
			
			role.add(rol);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
						<div id="main-content-ac">
        					
							<div class="imageFrame">แก้ไขบัญชีผู้ใช้</div>
							
							<br/><br/><br/><br/><br/><br/>
        					
        					<center>
        					<table width="800" border="0">
					       		<tr style="font-size:24px">
					           	  <td width="400" height="50">
					                	<label for="name"><font size="5"><strong>ชื่อ</strong></font></label>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<input type="hidden" name="name_old" id="name_old" value="<%=nameOld+" "+surnameOld %>" value="" list="namelist" onkeyup="search_name(this.value)" />
					                
					                	<input type="text" name="name" id="name" value="<%=nameOld+" "+surnameOld %>" value="" list="namelist" onkeyup="search_name(this.value)" />
					                	<datalist id="namelist">
										</datalist>
											
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<label for="username"> <font size="5"><strong>Username</strong></font> </label>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<input type="text" name="username" id="username" value="<%=usernameOld %>" readonly="readonly" />
					                </td>
					            </tr>
					            
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>Password</strong></font>
					                </td>
					                <td width="400" height="50" id="td_password">
					                	<input type="button" name="resetPassword" id="resetPassword" class="buttonStyle" value="reset" onclick="reset_password()" />
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px" id="tr_password_re">
					            	<td width="400" height="50">
					                	<font size="5"><strong>Re Password</strong></font>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<input type="password" id="passwordRe" name="passwordRe" />
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>หน่วยงาน</strong></font>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<select id="workgroup" >
												<option value="<%=workgroupId %>"> <%=workgroupOld %>  </option>
		<%
										for(Workgroup wg : workgroup) {
											if(wg.getWorkgroupId() != workgroupId) {
		%>
												<option value="<%=wg.getWorkgroupId() %>"> <%=wg.getWorkgroupName() %>  </option>
		<%
											}
										}
		%>										
												
										</select>		
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>สถานะ</strong></font>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<select id="status" >
		<%
										if("1".equals(status)) {
		%>
												<option value="1"> Active  </option>
												<option value="0"> Inactive  </option>
		<%
										}
										else {
		%>
											<option value="0"> Inctive  </option>
											<option value="1"> Active  </option>
		<%									
										}
		%>										
												
										</select>
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>วันที่เริ่มต้นใช้งาน</strong></font>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<input type="date" name="startDate" id="startDate" value="<%=startDateOld %>">
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>วันที่สิ้นสุดการใช้งาน</strong></font>
					                </td>
					                <td width="400" height="50">
					                	<input type="date" name="endDate" id="endDate" value="<%=endDateOld %>"> 
					                </td>
					            </tr>
					            
					             <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<font size="5"><strong>หน้าที่</strong></font>
					                	<label><font size="5" color="#FF0000">*</font></label>
					                </td>
					                <td width="400" height="50">
					                	<select name="role" id="role">
						                        <option value="select">เลือก</option>
				<%
										for(Role ro : role) {
				%>	
												<option value="<%=ro.getRoleId() %>"> <%=ro.getRoleName() %></option>
				<%
										}
				%>
										</select>
					                	<input type="button" name="add" id="add" value="add" style="width: 50px; height: 30px;"/>
					                	
					                </td>
					            </tr>
					            
					            <tr style="font-size:24px">
					            	<td width="400" height="50" colspan="2">
					                	<center>
					                	<table width="500" id="table_role_add" name="table_role_add">
					                		<tr>
						                		<td style="text-align: center; height: 30px;">
						                			ชื่อหน้าที่
						                		</td>
						                		
						                		<td style="height: 30px;">
						                			
						                		</td>
						                	</tr>
				<%
							int count = 0;
							for(Role rol : role_old) {
								count++;
							
				%>		                	
											<input type="hidden" id="roleId_add<%=count %>" name="roleId_add<%=count %>" value="<%=rol.getRoleId() %>" />
						                	<tr id="role_add<%=count %>" name="role_add<%=count %>" >
						                		<td style="height: 30px;" id="td_role_add<%=count %>">
						                			<%=rol.getRoleName() %>
						                		</td>
						                		
						                		<td style="height: 30px;">
						                			<center><span title="ลบข้อมูล">
						                				<input type="image" src="image/delete_icon.png" height="30px" width="30px" onclick="delete_role(<%=count %>, 'true')" />
						                			</span></center>
						                		</td>
						                	</tr>
				<%
							}
				%>
					                	</table>
					                	</center>
				                	<input type="hidden" id="num_role" name="num_role" value="<%=count %>" />
					                	
					                </td>
					            </tr>
					            
					            <tr>
					            	<td colspan="2">
					            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
					            	</td>
					            </tr>
					            
					             <tr style="font-size:24px">
					            	<td width="400" height="50">
					                	<center><input type="button" name="save" id="save"  value="save" class="buttonStyle"/></center>
					                </td>
					                <td width="400" height="50">
					                	<a href="admin_account.jsp"><button class="buttonStyle">cancel</button></a>
					                </td>
					            </tr>
					       </table>
						</center>
						
						<br><br><br>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>